package apis

import (
	"errors"
	"fmt"
	"github.com/go-playground/validator/v10"
	"net/http"
	"reflect"
	"strings"
	"sync"
	"vrcm/src/vrcm/common/storage"
	"vrcm/src/vrcm/sdk"

	"github.com/gin-gonic/gin"
	"github.com/gin-gonic/gin/binding"
	"github.com/go-admin-team/go-admin-core/logger"
	"github.com/go-admin-team/go-admin-core/sdk/api"
	"github.com/go-admin-team/go-admin-core/sdk/pkg"
	"github.com/go-admin-team/go-admin-core/sdk/pkg/response"
	"gorm.io/gorm"

	"vrcm/src/vrcm/common/service"
)

var vd = validator.New()

type Api struct {
	Context *gin.Context
	Logger  *logger.Helper
	Orm     *gorm.DB
	Redis   storage.AdapterCache
	Errors  error
}

const (
	_ uint8 = iota
	json
	xml
	yaml
	form
	query
)

var constructor = &bindConstructor{}

func (e *Api) AddError(err error) {
	if e.Errors == nil {
		e.Errors = err
	} else if err != nil {
		e.Logger.Error(err)
		e.Errors = fmt.Errorf("%v; %w", e.Error, err)
	}
}

// MakeContext 设置http上下文
func (e *Api) MakeContext(c *gin.Context) *Api {
	e.Context = c
	e.Logger = api.GetRequestLogger(c)
	e.Logger.Info(fmt.Sprintf("%s:body:%s ", c.Request.URL, c.Request.Body))
	return e
}

// GetLogger 获取上下文提供的日志
func (e Api) GetLogger() *logger.Helper {
	return api.GetRequestLogger(e.Context)
}

//func (e *Api) Bind(d interface{}, bindings ...binding.Binding) *Api {
//	var err error
//	if len(bindings) == 0 {
//		bindings = append(bindings, binding.JSON, nil)
//	}
//	for i := range bindings {
//		switch bindings[i] {
//		case binding.JSON:
//			err = e.Context.ShouldBindWith(d, binding.JSON)
//		case binding.XML:
//			err = e.Context.ShouldBindWith(d, binding.XML)
//		case binding.Form:
//			err = e.Context.ShouldBindWith(d, binding.Form)
//		case binding.Query:
//			err = e.Context.ShouldBindWith(d, binding.Query)
//		case binding.FormPost:
//			err = e.Context.ShouldBindWith(d, binding.FormPost)
//		case binding.FormMultipart:
//			err = e.Context.ShouldBindWith(d, binding.FormMultipart)
//		case binding.ProtoBuf:
//			err = e.Context.ShouldBindWith(d, binding.ProtoBuf)
//		case binding.MsgPack:
//			err = e.Context.ShouldBindWith(d, binding.MsgPack)
//		case binding.YAML:
//			err = e.Context.ShouldBindWith(d, binding.YAML)
//		case binding.Header:
//			err = e.Context.ShouldBindWith(d, binding.Header)
//		default:
//			err = e.Context.ShouldBindUri(d)
//		}
//		if err != nil {
//			e.AddError(err)
//		}
//	}
//	return e
//}

// Bind 参数校验
func (e *Api) Bind(d interface{}, bindings ...binding.Binding) *Api {
	var err error
	if len(bindings) == 0 {
		bindings = constructor.GetBindingForGin(d)
	}
	for i := range bindings {
		if bindings[i] == nil {
			err = e.Context.ShouldBindUri(d)
		} else {
			err = e.Context.ShouldBindWith(d, bindings[i])
		}
		if err != nil && err.Error() == "EOF" {
			e.Logger.Warn("request body is not present anymore. ")
			err = nil
			continue
		}
		if err != nil {
			e.AddError(err)
			break
		}
	}
	//vd.SetErrorFactory(func(failPath, msg string) error {
	//	return fmt.Errorf(`"validation failed: %s %s"`, failPath, msg)
	//})

	if err1 := vd.Struct(d); err1 != nil {
		e.AddError(err1)
	}
	return e
}

// GetOrm 获取Orm DB
func (e *Api) GetOrm() (*gorm.DB, error) {
	db, err := pkg.GetOrm(e.Context)
	if err != nil {
		e.Error(500, err, "数据库连接获取失败")
		return nil, err
	}
	return db, nil
}

// MakeOrm 设置Orm DB
func (e *Api) MakeOrm() *Api {
	var err error
	if e.Logger == nil {
		err = errors.New("at MakeOrm logger is nil")
		//e.Logger.Error(500, err, "at MakeOrm logger is nil")
		e.AddError(err)
		return e
	}
	db, err := pkg.GetOrm(e.Context)
	if err != nil {
		e.Logger.Error(500, err, "数据库连接获取失败")
		e.AddError(err)
	}

	e.Orm = db

	idb, exist := e.Context.Get("db")
	if !exist {
		e.AddError(errors.New("db connect not exist"))
	}
	switch idb.(type) {
	case storage.AdapterCache:
		//新增操作
		e.Redis = idb.(storage.AdapterCache)
	default:
		e.Redis = sdk.Runtime.GetCacheAdapter()
	}
	return e
}

func (e *Api) MakeService(c *service.Service) *Api {
	c.Log = e.Logger
	c.Orm = e.Orm
	c.Redis = e.Redis
	return e
}

// Error 通常错误数据处理
func (e *Api) Error(code int, err error, msg string) {
	response.Error(e.Context, code, err, msg)
}

// OK 通常成功数据处理
//func (e *Api) OK(data interface{}, msg string) {
//	response.OK(e.Context, data, msg)
//}

// PageOK 分页数据处理
func (e *Api) PageOK(result interface{}, count int, pageIndex int, pageSize int, msg string) {
	response.PageOK(e.Context, result, count, pageIndex, pageSize, msg)
}

// Custom 兼容函数
func (e *Api) Custom(data interface{}, codeType *CodeType) {
	content := gin.H{
		"code": codeType.Code,
		"msg":  codeType.Msg,
		"data": data,
	}
	response.Custum(e.Context, content)
}

type bindConstructor struct {
	cache map[string][]uint8
	mux   sync.Mutex
}

func (e *bindConstructor) GetBindingForGin(d interface{}) []binding.Binding {
	bs := e.getBinding(reflect.TypeOf(d).String())
	if bs == nil {
		//重新构建
		bs = e.resolve(d)
	}
	gbs := make([]binding.Binding, 0)
	mp := make(map[uint8]binding.Binding, 0)
	for _, b := range bs {
		switch b {
		case json:
			mp[json] = binding.JSON
		case xml:
			mp[xml] = binding.XML
		case yaml:
			mp[yaml] = binding.YAML
		case form:
			mp[form] = binding.Form
		case query:
			mp[query] = binding.Query
		default:
			mp[0] = nil
		}
	}
	for e := range mp {
		gbs = append(gbs, mp[e])
	}
	return gbs
}

func (e *bindConstructor) resolve(d interface{}) []uint8 {
	bs := make([]uint8, 0)
	qType := reflect.TypeOf(d).Elem()
	var tag reflect.StructTag
	var ok bool

	for i := 0; i < qType.NumField(); i++ {
		tag = qType.Field(i).Tag
		if _, ok = tag.Lookup("json"); ok {
			bs = append(bs, json)
		}
		if _, ok = tag.Lookup("xml"); ok {
			bs = append(bs, xml)
		}
		if _, ok = tag.Lookup("yaml"); ok {
			bs = append(bs, yaml)
		}
		if _, ok = tag.Lookup("form"); ok {
			bs = append(bs, form)
		}
		if _, ok = tag.Lookup("query"); ok {
			bs = append(bs, query)
		}
		if _, ok = tag.Lookup("uri"); ok {
			bs = append(bs, 0)
		}
		if t, ok := tag.Lookup("binding"); ok && strings.Index(t, "dive") > -1 {
			qValue := reflect.ValueOf(d)
			bs = append(bs, e.resolve(qValue.Field(i))...)
			continue
		}
		if t, ok := tag.Lookup("validate"); ok && strings.Index(t, "dive") > -1 {
			qValue := reflect.ValueOf(d)
			bs = append(bs, e.resolve(qValue.Field(i))...)
		}
	}
	return bs
}

func (e *bindConstructor) getBinding(name string) []uint8 {
	e.mux.Lock()
	defer e.mux.Unlock()
	return e.cache[name]
}

func (e *bindConstructor) setBinding(name string, bs []uint8) {
	e.mux.Lock()
	defer e.mux.Unlock()
	if e.cache == nil {
		e.cache = make(map[string][]uint8)
	}
	e.cache[name] = bs
}

func (e *Api) OK(data interface{}, msg string) {
	e.Context.JSON(http.StatusOK, gin.H{
		"requestId": pkg.GenerateMsgIDFromContext(e.Context),
		"code":      200,
		"message":   msg,
		"data":      data,
	})
}
